<template>
  <div class="app-container">
    <!-- <mainTilte title="供应商管理" /> -->
    <!-- <el-form ref="searchParams" size="small" :inline="true" :model="searchParams" label-width="110px">
      <div class="filters-wrap clearfix">
        <div class="filters-area">
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-select v-model.trim="searchParams.type" clearable placeholder="供应商编码">
                <el-option v-for="(item, index) of issignContract" :key="index" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-input v-model.trim="searchParams.value" placeholder="关键字回车搜索" @keyup.enter.native="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-select v-model.trim="searchParams.audit_status" clearable placeholder="状态" @change="handleSearch">
                <el-option v-for="(item, index) of statusList" :key="index" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </div>
    </el-form> -->
    <div class="mb10">
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch">
        <div>
          <el-button size="mini" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </form-selections>
    </div>

    <div class="page-grid">
      <div class="action-group">
        <el-button v-action="'supply@save'" size="small" type="success" element-loading-text="正在执行请稍后" icon="el-icon-circle-plus-outline" @click="bulkShipment">新增供应商</el-button>
        <el-button v-action="'supply@SubmitAudit'" size="small" type="primary" element-loading-text="正在执行请稍后" @click="submitReviewClick">提交审核</el-button>
        <el-button v-action="'supply@changeAuditStatus'" size="small" type="primary" element-loading-text="正在执行请稍后" @click="auditClick">审核</el-button>
        <el-button v-action="'supply@setContractTemplate'" size="small" type="primary" element-loading-text="正在执行请稍后" @click="setTemplateClick">设置合同模板</el-button>
        <el-button v-action="'supply@changeCooperationStatus'" size="small" type="primary" element-loading-text="正在执行请稍后" @click="terminationClick(0)">终止</el-button>
        <el-button v-action="'supply@changeCooperationStatus'" size="small" type="primary" element-loading-text="正在执行请稍后" @click="terminationClick(1)">恢复</el-button>
      </div>
      <egrid v-loading="loading" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" :screen-heigh="screenHeigh" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 新增供应商 -->
    <el-dialog v-if="dialogAddVisible" v-loading.lock="loading" v-loading="loading" :title="title" :visible.sync="dialogAddVisible" :close-on-click-modal="true" width="60%" class="dialogText header-none" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center :destroy-on-close="true" @close="closeHandler">
      <el-form v-if="dialogAddVisible" ref="form" :model="form" :rules="roleCodeRule" label-width="120px" :disabled="isInfoSupplierForm">
        <el-row>
          <mainTilte title="基本信息" />
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商代码" prop="code">
              <el-input v-model.trim="form.code" maxlength="30" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model.trim="form.name" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结算周期" prop="billing_cycles">
              <el-input v-model.trim="form.billing_cycles" maxlength="5" oninput="value=value.replace(/[^0-9-]/g,'')">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="采购员" prop="buyer">
              <el-select v-model="form.buyer" multiple clearable filterable placeholder="请选择" class="multiple-style">
                <el-option v-for="item in buyerList" :key="item.id" :value="item.username" :label="item.username" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model.trim="form.contacts" maxlength="10" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人手机" prop="contacts_phone">
              <el-input v-model="form.contacts_phone" oninput="value=value.replace(/[^0-9-]/g,'')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定电话" prop="phone">
              <el-input v-model="form.phone" oninput="value=value.replace(/[^0-9-]/g,'')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="传真" prop="fax">
              <el-input v-model.trim="form.fax" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model.trim="form.address" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮编" prop="zipcode">
              <el-input v-model.trim="form.zipcode" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预付款比例" prop="pay_ratio">
              <el-input v-model.trim="form.pay_ratio" maxlength="100" oninput="value=value.replace(/[^0-9-]/g,'')">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注说明" prop="notes">
              <el-input v-model="form.notes" maxlength="500" type="textarea" autosize />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mainTilte title="账户信息" />
        </el-row>
        <el-row style="margin-bottom: 10px">
          <el-button type="primary" icon="el-icon-circle-plus" @click="addaccount">添加账号</el-button>
        </el-row>
        <el-table ref="singleTable" :data="form.account" stripe fit border>
          <el-table-column fixed="left" label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #ff4444" @click="deleteClick(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="币别" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'account.' + scope.$index + '.currency'" class="no-label mt22" :rules="[
                  {
                    required: true,
                    message: '请输入币别',
                    trigger: 'blur',
                  },{
                    required: true,
                    message: '请输入币别',
                    trigger: 'change',
                  },
                ]">
                <app-select v-model="scope.row.currency" url="/currency" :params="selectParams" options-label="source_name" options-value="source_code" placeholder="请选择币别" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="bank" label="开户行" width="180" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'account.' + scope.$index + '.bank'" class="no-label mt22" :rules="[
                  {
                    required: true,
                    message: '请输入开户行',
                    trigger: 'blur',
                  },{
                    required: true,
                    message: '请输入开户行',
                    trigger: 'change',
                  },
                ]">
                <el-input v-model.trim="scope.row.bank" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="bank_account" label="银行账号" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'account.' + scope.$index + '.bank_account'" class="no-label mt22" :rules="bankNumberRule">
                <el-input v-model.trim="scope.row.bank_account" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <mainTilte title="资质信息" />
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="营业执照" prop="business_license">
              <uploadFile list-type="text" text="上传支持图片、pdf格式" :file-list="fileList" :upload-limit="1" accept-type="image/jpeg,image/png,application/pdf" @handleImageSuccess="handleImageSuccess" @beforeRemoveFile="beforeRemoveFile" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span v-if="isInfoSupplierForm" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeHandler">返回</el-button>
      </span>
      <span v-else slot="footer" class="dialog-footer">
        <el-button :loading="canSaveLoading" type="primary" @click="saveData()">保存</el-button>
        <el-button @click="dialogAddVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 设置合同模板 -->
    <el-dialog v-if="setTemplateVisible" :title="title" :visible.sync="setTemplateVisible" :close-on-click-modal="true" width="60%" class="dialogText header-none" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center :destroy-on-close="true">
      <el-form v-if="setTemplateVisible" ref="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同模板">
              <ckEditor :past-editor.sync="contract_template" :is-read-only="false" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveTemplateData()">保存</el-button>
        <el-button @click="setTemplateVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 审核 -->
    <auditDialog ref="auditDialog" :isaudit-visible="isauditVisible" :file-list="fileListAudit" :form="checkedList[0]" :buyer-list="buyerList" @saveAuditData="saveAuditData" @cancelIsauditVisible="cancelIsauditVisible" />
  </div>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import dicValues from '@/components/dicTransform/index'
import auditDialog from './components/auditDialog'
import codeItem from '@/components/base/code'
import { getFileId, filterId, fileTransform } from '@/filters/index'
import {
  isPoneAvailable,
  validChineseOrs
} from '@/utils/validate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import appText from '@/components/appText/index'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'Supplier',
  components: { auditDialog },
  directives: {
    action
  },
  mixins: [list, cacheList, formOperate],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 审核状态 0 待提交 1 待审核 2 已审核 -1 审核驳回
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待审核'
        },
        {
          code: 2,
          name: '审核通过'
        },
        {
          code: -1,
          name: '审核驳回'
        }
      ],
      // 合作状态 1-正常  0-终止
      cooperationStatus: [
        { code: 0, name: '终止' },
        {
          code: 1,
          name: '正常'
        }
      ]
    }
    const checkBilling = (rule, value, callback) => {
      if (value > 1000) {
        callback(new Error('结算周期须小于1000天'))
      } else {
        callback()
      }
    }
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (isPoneAvailable(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const codeClickHandler = (name) => {
      const item = this.tableData.find((e) => e.name === name)
      item.buyer =
        item.buyer && typeof item.buyer === 'string'
          ? item.buyer.split(',')
          : item.buyer
      // this.form = JSON.parse(JSON.stringify(item))
      this.form.id = item.id
      this.form.code = item.code // 供应商代码
      this.form.name = item.name // 供应商名称
      this.form.billing_cycles = item.billing_cycles // 结算周期
      this.form.buyer = item.buyer // 采购员
      this.form.contacts = item.contacts // 联系人
      this.form.contacts_phone = item.contacts_phone // 联系电话
      this.form.phone = item.phone // 固定电话
      this.form.fax = item.fax // 传真
      this.form.address = item.address // 地址
      this.form.zipcode = item.zipcode // 邮编
      this.form.pay_ratio = item.pay_ratio // 预付款比例
      this.form.notes = item.notes // 备注说明
      this.form.business_license = item.business_license // 营业执照
      this.fileList = fileTransform(item.business_license)
      this.form.account = item.bank_accounts
      this.dialogAddVisible = true
      this.isInfoSupplierForm = true
    }
    return {
      formItems: [
        {
          label: '供应商编码',
          key: 'code',
          type: 'input',
          placeholder: '请输入供应商编码'
        },
        {
          label: '供应商名称',
          key: 'name',
          type: 'input',
          placeholder: '请输入供应商名称'
        },
        // {
        //   label: '采购员',
        //   key: 'buyer',
        //   type: 'input',
        //   placeholder: '请输入采购员名称'
        // },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待审核'
            },
            {
              value: 2,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        }
      ],
      componentName: 'Supplier',
      bankNumberRule: [
        { required: true, message: '请输入银行账号', trigger: 'blur' },
        { pattern: /^[0-9a-zA-Z]*$/, message: '银行账号必须为数字或字母组成', trigger: 'blur' },
        { max: 50, message: '银行账号必须在50个字符以内', trigger: 'blur' }
      ],
      canSaveLoading: false,
      statusList: [
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待审核'
        },
        {
          code: 2,
          name: '审核通过'
        },
        {
          code: -1,
          name: '审核驳回'
        }
      ],
      value: '',
      value1: [],
      loading: false,
      dialogAddVisible: false, // 新增供应商弹框
      title: '',
      loadingText: '',
      rule: {},
      searchForm: {},
      /** *
       * 定义搜索框
       */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        pageSizeX: [10, 20, 30, 40, 50, 100], // 每页显示个数选择器的选项设置
        code: '',
        name: '',
        buyer: '',
        audit_status: ''
      },
      /** *
       * 定义显示的表格
       */
      columns: [
        {
          label: '供应商代码',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '供应商名称',
          prop: 'name',
          minWidth: '150',
          align: 'center',
          tooltip: false
        },
        {
          label: '是否设置合同',
          prop: 'contract_template',
          width: '100',
          align: 'center',
          component: appText,
          propsHandler({ row }) {
            return { text: row.contract_template ? '是' : '否' }
          }
        },
        // {
        //   label: '联系人',
        //   prop: 'contacts',
        //   width: '150',
        //   align: 'center',
        //   tooltip: false
        // },
        // {
        //   label: '联系人手机号',
        //   prop: 'contacts_phone',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false
        // },
        {
          label: '预付比例(%)',
          prop: 'pay_ratio',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '结算周期',
          prop: 'billing_cycles',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '合作状态',
          prop: 'cooperation_status',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核状态',
          prop: 'audit_status',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核原因',
          prop: 'audit_notes',
          width: '100',
          align: 'center',
          component: appText,
          propsHandler({ row }) {
            return { text: row.audit_notes }
          }
        },
        {
          label: '创建人',
          prop: 'created_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'updated_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],

      /** *
       * 字典表组件
       */
      columnsSchema: {
        供应商名称: {
          propsHandler({ col, row }) {
            return {
              code: row[col.prop]
            }
          },
          listeners: {
            click: codeClickHandler
          },
          component: codeItem
        },
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        合作状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      issignContract: [
        {
          name: '供应商编码',
          code: 'code'
        },
        {
          name: '供应商名称',
          code: 'name'
        },
        {
          name: '采购员',
          code: 'buyer'
        }
      ],
      form: {
        id: '',
        code: null, // 供应商代码
        name: null, // 供应商名称
        billing_cycles: null, // 结算周期
        buyer: null, // 采购员
        contacts: null, // 联系人
        contacts_phone: null, // 联系电话
        phone: null, // 固定电话
        fax: null, // 传真
        address: null, // 地址
        zipcode: null, // 邮编
        pay_ratio: null, // 预付款比例
        notes: null, // 备注说明
        account: [],
        business_license: null // 营业执照
      },
      bareColumn: [
        {
          label: '币别',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        },
        {
          label: '开户行',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        },
        {
          label: '银行账号',
          prop: 'suppierCode',
          align: 'center',
          minWidth: 50,
          tooltip: false
        }
      ],
      bareColumnsSchema: {},
      loadingBare: false,
      roleCodeRule: {
        code: [
          { required: true, message: '供应商代码不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              // 包含了中文
              validChineseOrs(value)
                ? callback(new Error('供应商代码不能包含中文'))
                : callback()
            },
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '供应商名称不能为空', trigger: 'blur' },
          { max: 100, message: '供应商名称必须在100个字符以内', trigger: 'blur' }
        ],
        billing_cycles: [
          { required: true, message: '请输入结算周期', trigger: 'blur' },
          { validator: checkBilling, trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        contacts_phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        business_license: [
          { required: true, message: '营业执照不能为空', trigger: 'change' }
        ]
        // phone: [
        //   { required: false, validator: checkMob, },
        // ],
        // currency:[
        //   { required: true, message: '营业执照不能为空', trigger: 'change' },
        // ],
      },
      setTemplateVisible: false, // 设置合同模板弹框
      contract_template: '', // 合同模板值
      buyerList: [], // 采购员列表
      isauditVisible: false,
      isEditSupplierForm: false, // 是否为编辑
      isInfoSupplierForm: false,
      fileList: [],
      fileListAudit: [],
      selectParams: {
        page: 1,
        limit: 100000000,
        status: 1
      },
      defaultContract: ''
    }
  },
  mounted() {
    this.initSearchData()
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js）
    this.query()
    this.getBuyerData()
    this.getDefaultContract() // 获取默认合同
  },
  activated() {
    this.query()
  },
  methods: {
    getDefaultContract() {
      const vm = this
      vm.$http.get('/config/defaultContract').then(res => {
        vm.defaultContract = res.data.defaultContract.supplier
      })
    },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh(isRefreshPage) {
      const vm = this
      if (isRefreshPage) {
        vm.searchParams.page = 1
      }
      vm.searchParams.limit = 10
      vm.searchParams.name = ''
      vm.searchParams.code = ''
      vm.searchParams.buyer = ''
      vm.searchParams.audit_status = ''
      vm.query()
    },
    closeHandler() {
      const vm = this
      vm.isEditSupplierForm = false
      vm.isInfoSupplierForm = false
      vm.dialogAddVisible = false
      vm.initFormData()
    },
    initSearchData() {
      this.searchParams.page = 1
      this.searchParams.limit = 10
      this.searchParams.totalRows = 0
      this.searchParams.buyer = ''
      this.searchParams.code = ''
      this.searchParams.name = ''
      this.searchParams.audit_status = ''
    },
    // 点击搜索
    query() {
      const vm = this
      let url = '/supply'
      const { page, limit, code, name, buyer, audit_status } = vm.searchParams
      url += `?page=${page}&limit=${limit}&audit_status=${audit_status}&name=${name}&code=${code}&buyer=${buyer}`
      // if (type) {
      //   url += `&${type}=${value}`
      // }
      this.initTableData(url)
    },
    initFormData() {
      this.form.id = ''
      this.form.code = null // 供应商代码
      this.form.name = null // 供应商名称
      this.form.billing_cycles = null // 结算周期
      this.form.buyer = null // 采购员
      this.form.contacts = null // 联系人
      this.form.contacts_phone = null // 联系电话
      this.form.phone = null // 固定电话
      this.form.fax = null // 传真
      this.form.address = null // 地址
      this.form.zipcode = null // 邮编
      this.form.pay_ratio = null // 预付款比例
      this.form.notes = null // 备注说明
      this.form.account = []
      this.form.business_license = null // 营业执照
      this.fileList = []
    },
    // 新增供应商
    bulkShipment() {
      this.initFormData()
      this.isEditSupplierForm = false // 新增
      this.dialogAddVisible = true
    },
    // 新增/编辑-保存
    saveData() {
      const form = this.$refs['form']
      form.validate((valid) => {
        // 验证方法
        if (valid) {
          // 验证银行账号 是否重复
          const accountList = this.form.account
          if (accountList.length <= 0) {
            return this.$message.error('请选择添加至少一个账号')
          }
          if (accountList.length > 1) {
            const accountSet = new Set(accountList.map(e => e.bank_account))
            if (accountSet.size !== accountList.length) {
              return this.$message.error('银行卡号不能重复')
            }
          }
          this.canSaveLoading = true
          const params = Object.assign({}, this.form)
          params.buyer = params.buyer.join(',')
          if (!params.pay_ratio) {
            params.pay_ratio = 0
          }
          // 新增
          if (!this.isEditSupplierForm) {
            delete params.id
            this.$http
              .post(`/supply`, params)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('提交成功')
                  this.query()
                }
                this.canSaveLoading = false
                this.dialogAddVisible = false
              })
              .catch((err) => {
                console.log(err)
                this.canSaveLoading = false
              })
          } else {
            delete params.updated_at
            delete params.created_at
            if (!params.pay_ratio) {
              params.pay_ratio = 0
            }
            this.$http
              .put(`/supply/${this.form.id}`, params)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('提交成功')
                  this.query()
                  this.canSaveLoading = false
                  this.dialogAddVisible = false
                }
              })
              .catch((err) => {
                this.canSaveLoading = false
                console.log(err)
              })
          }
        }
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '135',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          // 审核状态 不是审核通过 || 合作状态0-终止
          const isShowHandler =
            row.audit_status !== 2 || row.cooperation_status === 0
          return {
            row: row,
            edit: isShowHandler,
            del: isShowHandler,
            delAction: 'supply@delete',
            editAction: 'supply@update'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          deleteTableClick(row) {
            that
              .$confirm('您确定要删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.loading = true
                // 点击确定
                that.$http
                  .delete(`/supply/${row.id}`)
                  .then((res) => {
                    that.loading = false
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch(() => {
                    that.loading = false
                  })
              })
              .catch(() => {
                that.loading = false
              })
          },
          editTableClick(row) {
            row.buyer =
              row.buyer && typeof row.buyer === 'string'
                ? row.buyer.split(',')
                : row.buyer
            that.fileList = fileTransform(row.business_license)
            that.form = JSON.parse(JSON.stringify(row))
            that.form.account = row.bank_accounts
            that.isEditSupplierForm = true // 编辑
            that.dialogAddVisible = true
          }
        }
      })
    },
    bareColumnsHandler(cols) {
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          return { row: row }
        },
        // component: btnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          view(row) { }
        }
      })
    },
    // 添加账号
    addaccount() {
      if (this.form.account.length > 9) {
        return
      }
      this.form.account.push({
        currency: null, // 币种
        bank: null, // 开户行
        bank_account: null // 账号信息
      })
    },
    // 点击设置合同模板
    setTemplateClick() {
      const that = this
      const dataLength = that.checkedList.length
      if (dataLength === 0) {
        that.$message.error('至少选择一条数据')
        return false
      }
      if (dataLength > 1) {
        return that.$message.error('至多选择一条数据')
      }
      that.setTemplateVisible = true
      that.contract_template = that.checkedList[0].contract_template || that.defaultContract
    },
    // 设置合同模板-保存
    saveTemplateData() {
      const that = this
      if (!that.contract_template.includes('{{selletment_date}}') || !that.contract_template.includes('{{total_amount}}')) {
        return that.$message.error('输入的合同模板有误!')
      }
      const params = {
        ids: that.ids,
        contract_template: that.contract_template
      }
      that.$http
        .post(`/supply/set-contract-template`, params)
        .then((res) => {
          if (res.code === 10000) {
            that.$message.success('设置成功')
            that.query()
          }
        })
        .catch((err) => {
          console.log(err)
        })
      that.setTemplateVisible = false
    },
    // 点击提交审核按钮
    submitReviewClick() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      // 判断所选的数据是否都是待提交
      const every = this.checkedList.every((e) => e.audit_status === 0 || e.audit_status === -1)
      if (!every) {
        return this.$message.error('所选数据必须是待提交状态')
      }
      // for (var i = 0; i < this.checkedList.length; i++) {
      //   if (this.checkedList[i].audit_status != 0) {
      //     this.$message.warning("请选择待提交的数据");
      //     return;
      //   }
      // }
      this.$confirm(`确定提交审核吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/supply/submit-audit`, { ids: this.ids })
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('提交审核成功')
              this.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 点击终止按钮 0-终止 1-恢复
    terminationClick(type) {
      const vm = this
      const typeText = type === 0 ? '正常' : '终止'
      const dataLength = vm.checkedList.length
      const queryPara = {
        ids: vm.ids,
        cooperation_status: type
      }
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      for (var i = 0; i < vm.checkedList.length; i++) {
        if (vm.checkedList[i].cooperation_status === type) {
          vm.$message.error(`请选择合作${typeText}的数据`)
          return
        }
      }
      vm.$confirm(`确定批量${type === 0 ? '终止' : '恢复'}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/supply/change-cooperation-status`, queryPara)
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('设置成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 采购员数据
    getBuyerData() {
      this.$http
        .get(`/shops/buyers`, { params: { status: 1 } })
        .then((res) => {
          if (res.code === 10000) {
            this.buyerList = res.data.buyers.filter(e => e.status === 1)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 点击审核
    auditClick() {
      const dataLength = this.checkedList.length
      this.fileListAudit = []
      this.fileListAudit = fileTransform(this.checkedList[0].business_license)
      this.form.business_license = getFileId(this.fileListAudit)
      if (dataLength === 0 || dataLength > 1) {
        this.$message.error('最多选择一条数据')
        return false
      }
      // 判断所选数据是否都是 待审核状态
      const every = this.checkedList.every((e) => e.audit_status === 1)
      if (!every) {
        this.$message.error('所选数据必须都是待审核状态')
        return
      }

      // for (var i = 0; i < this.checkedList.length; i++) {
      //   if (this.checkedList[i].audit_status != 1) {
      //     this.$message.warning(`请选择一条待审核的数据`);
      //     return;
      //   }
      // }
      this.isauditVisible = true
      this.$refs.auditDialog.resetForm()
    },
    cancelIsauditVisible() {
      this.isauditVisible = false
    },
    // 审核保存
    saveAuditData(auditForm) {
      this.$http
        .post(`/supply/change-audit-status`, auditForm)
        .then((res) => {
          if (res.code === 10000) {
            this.$message.success('审核成功')
            this.query()
          }
        })
        .catch((err) => {
          console.log(err)
        })
      this.isauditVisible = false
    },
    handleImageSuccess({ name, url }) {
      this.fileList.push({ name, url })
      this.form.business_license = getFileId(this.fileList)
    },
    beforeRemoveFile(file) {
      this.fileList = filterId(this.fileList, file)
      this.form.business_license = getFileId(this.fileList)
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    },
    deleteClick(row) {
      this.form.account = this.form.account.filter((item) => {
        return item !== row
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-cascader {
  width: 100%;
}
/deep/.el-select,
.el-autocomplete,
.el-cascader {
  width: 100%;
}
</style>
